import 'package:flutter/material.dart';

import '../utils/global_context.dart';

class PopupItem {
  final IconData icon;
  final String text;
  final VoidCallback onTap;

  PopupItem({
    required this.icon,
    required this.text,
    required this.onTap,
  });
}

class Popup {
  static Future<void> show({
    required Offset position,
    required List<PopupItem> items,
    double maxWidth = 90,
  }) async {
    final List<PopupMenuEntry<PopupItem>> menuItems = [];

    for (var i = 0; i < items.length; i++) {
      final item = items[i];

      menuItems.add(
        PopupMenuItem<PopupItem>(
          value: item,
          height: 40,
          padding: EdgeInsets.zero,
          child: ConstrainedBox(
            constraints: BoxConstraints(maxWidth: maxWidth),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: Row(
                children: [
                  Icon(item.icon, size: 16, color: Colors.blueGrey),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      item.text,
                      style: const TextStyle(fontSize: 13),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      if (i != items.length - 1) {
        menuItems.add(
          const PopupMenuItem<PopupItem>(
            enabled: false,
            height: 1,
            padding: EdgeInsets.zero,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 8),
              child: Divider(
                height: 1,
                thickness: 0.5,
                color: Colors.grey,
              ),
            ),
          ),
        );
      }
    }

    final selected = await showMenu<PopupItem>(
      context: globalContext!,
      position: RelativeRect.fromLTRB(
        position.dx,
        position.dy,
        position.dx,
        position.dy,
      ),
      items: menuItems,
      elevation: 8,
    );

    if (selected != null) {
      selected.onTap();
    }
  }
}






